package newui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.mywork.WorkUIKit;
import com.netease.nim.demo.contact.cache.ContactDataCache;
import com.netease.nim.demo.contact.cache.TeamDataCache;
import com.netease.nim.demo.contact.model.Buddy;
import com.netease.nim.demo.contact.protocol.ContactHttpClient;
import com.netease.nim.demo.contact.protocol.IContactHttpCallback;
import com.netease.nim.demo.main.activity.ContactMainActivity;
import com.netease.nim.demo.main.reminder.ReminderItem;
import com.netease.nim.demo.main.reminder.ReminderManager;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.shwread.android.qysw.activity.BaseBusinessActivity;
import com.shwread.android.qysw.activity.MessageActivity;
import com.shwread.android.qysw.activity.NewInteractionCenterUserPublishActivity;
import com.shwread.android.qysw.activity.WithMeRelatedActivity;
import com.shwread.android.qysw10000243.R;
import com.shwread.android.ui.dialog.GuideDialog;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;
import com.shwread.httpsdk.http.callback.BaseAction;
import com.shwread.httpsdk.http.face.QryUnReadActivityAction;
import com.shwread.httpsdk.http.face.QryUnReadTotalAction;
import com.shwread.httpsdk.util.NetUtil;

import org.apache.http.Header;
import org.geometerplus.android.util.QyreaderPerferencesUtil;

import java.lang.reflect.Type;
import java.util.List;

import logic.bean.AboutMeCount;
import logic.constants.Const;
import logic.constants.DefaultConsts;
import logic.util.NetworkUtil;
import newui.view.MomentContentView;

/**
 * Created by lex on 2017/7/17.
 */

public class MomentActivity extends BaseBusinessActivity implements
        View.OnClickListener,
        ReminderManager.UnreadNumChangedCallback {

    private View titleView;
    private View addView;
    private PullToRefreshScrollView contentView;

    // added by zouqp
    private LinearLayout ll_interaction_contentview;
    public MomentContentView contentItemView;

    private int pagetype;                  // 页面类型 0普通用户   1经理   2 为客户
    /**
     * 没有网络0 ，没有主题1
     */
    private int net_theme = 3;

    private LinearLayout nonet_theme_ll;
    private Button setnet;
    private ImageView no_nettheme_img;
    private TextView no_nettheme_tv;
    private AnimationDrawable postmsgAnimation;
    private LinearLayout meRelatedInputBoxLl;
    private TextView meRelatedCountTv;
    private RelativeLayout meRelatedRl, meRelatedButtonLl;
    public static int width, height;
    private Button btnBack;

    private int userPositionMark = -1;//根据userPositionMark判断是老师还是学生8: 老师  10:学生
    private int releaseType = -1;// releaseType 非必填 默认0：按照之前逻辑处理|1：老师发布内容|2：学生发布内容|3：问答区内容


    private static final String TAG = "MomentActivity";
    private Handler handler = new Handler();
    private TextView tvTitle;

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moment);


        Intent intent = getIntent();
        releaseType = intent.getIntExtra("releaseType", -1);
        if (releaseType == -1) {
            return;
        }
        userPositionMark = WorkUIKit.getUser().getUserPositionMark();

        initView();
        WindowManager manage = getWindowManager();
        width = manage.getDefaultDisplay().getWidth();
        height = manage.getDefaultDisplay().getHeight();

        setListener();
        initGuide();
        setPageInfo();

        // observers
        TeamDataCache.getInstance().init();

        prepareCacheData();

        new Handler(getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                prepareRemoteData();
            }
        }, 500);


        //		showGuide();
        if (NetworkUtil.isNetAvailable(this)) {
            setPageInfo();
            // clearPage();
            contentItemView.setFromType(pagetype);
            contentItemView.updateSwitchView(0);// 加载动画
            contentItemView.getInteractionData(0);// 初始装载
            contentItemView.getInteractionData(1);
            //			rlayNoNetTopTip.setVisibility(View.GONE);
        } else {
            //			new NoNetDialog(bActivity).show();
            //			rlayNoNetTopTip.setVisibility(View.VISIBLE);
        }
        qryUnReadTotal();
        registerMsgUnreadInfoObserver(true);
        registerSystemMessageObservers(true);
    }

    private void prepareCacheData() {
        ContactHttpClient.getInstance().getTokenOnLogin();
        ContactDataCache.getInstance().initBuddyCache(null);
        TeamDataCache.getInstance().initTeamCache();
    }

    private void prepareRemoteData() {
        // request buddies data
        if (!ContactDataCache.getInstance().isBuddyCacheDataEmpty()) {
            return;
        }

        Log.i(TAG, "request buddies data...");
        ContactHttpClient.getInstance().getAddressBook(new IContactHttpCallback<List<Buddy>>() {
            @Override
            public void onSuccess(List<Buddy> buddies) {
                ContactDataCache.getInstance().addOrUpdateBuddies(buddies);
//                Log.i(TAG, "request buddies data completed, data size =" + buddies.size());
            }

            @Override
            public void onFailed(int code, String errorMsg) {

            }
        });
    }

    @SuppressLint("UseSparseArrays")
    void initView() {
        //		relTitle = (RelativeLayout) findViewById(R.id.new_common_title_layout);
        //		relTitle.setVisibility(View.GONE);
        //		rlayNoNetTopTip = (RelativeLayout) findViewById(R.id.new_i_no_net_top_tip_rlay);
        		tvTitle = (TextView) findViewById(R.id.common_header_name);
//        		tvTitle.setText(this.getString(R.string.maintab_interaction));
        tvTitle.setVisibility(View.VISIBLE);
        if (releaseType==1){
            tvTitle.setText("教师分享");
        }
        if (releaseType==2){
            tvTitle.setText("公共论坛");
        }
        if (releaseType==3){
            tvTitle.setText("求助区");
        }
        //		// 普通用户的title图片
        //		ivPersion = (Button) findViewById(R.id.new_common_heoader_persion);
        //		// 普通用户的消息红点
        //		ivPersionRedDot = (ImageView) findViewById(R.id.new_common_header_persion_red_dot);
        //		ivPersionRedDot.setVisibility(View.GONE);
        //		// 经理的title图片
        //		ivManager = (Button) findViewById(R.id.new_common_header_manager);
        //		// 经理的消息红点
        //		ivManagerRedDot = (ImageView) findViewById(R.id.new_common_header_manager_red_dot);
        //		ivManagerRedDot.setVisibility(View.GONE);
        //		// title的设置按钮
        //		ivSetting = (Button) findViewById(R.id.new_common_header_setting);
        //		// 联系人未读红点
        //		ivNewMsg = (Button) findViewById(R.id.new_common_header_linkman_newmsg);
        //
        //		// 显示未读消息的layout
        //		messageLayout = findViewById(R.id.new_common_header_msg_layout);
        //		messageLayout.setVisibility(View.VISIBLE);
        //		// 未读消息小红点
        //		ivMsgUnread = (ImageView) findViewById(R.id.new_common_header_msg_unread_flag);
        //
        //		addView = findViewById(R.id.new_interaction_test_add_layout);
        //		addView.setOnClickListener(this);

        btnBack = (Button) findViewById(R.id.common_header_back);
        btnBack.setVisibility(View.VISIBLE);
        btnBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MomentActivity.this.finish();
            }
        });

        ll_interaction_contentview = (LinearLayout) findViewById(R.id.ll_interaction_contentview);
        // 标题栏--做双击回顶部
        titleView = findViewById(R.id.new_common_title_layout);
        // 发布主题
        postmsg = (ImageView) findViewById(R.id.new_interaction_center_postmsg);
        postmsg.setVisibility(View.GONE);
        no_nettheme_img = (ImageView) findViewById(R.id.new_interaction_no_theme_img);
        // 设置网络按钮
        setnet = (Button) findViewById(R.id.new_interaction_no_theme_btn_setting);
        // 没网络或没主题的提示文字
        no_nettheme_tv = (TextView) findViewById(R.id.new_interaction_no_theme_tv_text);
        contentView = (PullToRefreshScrollView) findViewById(R.id.iteraction_center_view);
        nonet_theme_ll = (LinearLayout) findViewById(R.id.new_no_theme_ll);
        meRelatedRl = (RelativeLayout) findViewById(R.id.me_related_click_rl);
        meRelatedRl.setVisibility(View.GONE);
        if (releaseType == 1 && userPositionMark == 8) {
            meRelatedRl.setVisibility(View.VISIBLE);
        }
        if (releaseType == 3 && (userPositionMark == 10 || userPositionMark == 8)) {
            meRelatedRl.setVisibility(View.VISIBLE);
        }
        if (releaseType == 2 && userPositionMark == 10) {
            meRelatedRl.setVisibility(View.VISIBLE);
        }
        meRelatedInputBoxLl = (LinearLayout) findViewById(R.id.me_related_input_box_ll);
        meRelatedButtonLl = (RelativeLayout) findViewById(R.id.me_related_button_ll);
        meRelatedCountTv = (TextView) findViewById(R.id.me_related_count_tv);
        if (net_theme == 1) {// 没主题
            contentView.setVisibility(View.GONE);
            nonet_theme_ll.setVisibility(View.VISIBLE);
            setnet.setVisibility(View.GONE);
            no_nettheme_tv.setText("没有主题哦，立即发布！");
            no_nettheme_img.setBackgroundResource(R.drawable.new_i_no_theme_icon);
            postmsg.setBackgroundResource(R.drawable.new_i_publish);
            postmsgAnimation = (AnimationDrawable) postmsg.getBackground();
            postmsgAnimation.start();
        } else if (net_theme == 0) {// 没网络
            contentView.setVisibility(View.GONE);
            nonet_theme_ll.setVisibility(View.VISIBLE);
        }

        PullToRefreshUtil.initLabel(this, contentView);

        // 增加内容项视图
        if (Const.UserRole.equals("0")) {
            pagetype = 0;// 普通用户
        } else if (Const.UserRole.equals("1")) {
            pagetype = 1;//客户经理
        } else if (Const.UserRole.equals("2")) {
            pagetype = 2;//客户
        }
        NewActionHelp.qryReplyRelateMeCount(this, new GetAboutMeCount());
        contentItemView = new MomentContentView(this, releaseType);
        contentItemView.setFromType(pagetype);
        contentItemView.setBaseActivity(this);
        contentItemView.setInteractionContentViewListener(new MomentContentView.InteractionContentViewListener() {
            @Override
            public void OnLoadDataCompleted(int flag) {
                if (flag == 0) {
                    // 首次装载
                    contentView.onRefreshComplete();
                } else if (flag == 1) { // 刷新装载
                    contentView.onRefreshComplete();
                } else if (flag == 2) {// 装载更多
                    contentView.onRefreshComplete();
                }
            }
        });
        clearPage();
    }

    private class GetAboutMeCount
            extends
            ObjectHttpResponseHandler<AboutMeCount> {

        @Override
        public Type getType() {
            return new TypeToken<AboutMeCount>() {
            }.getType();
        }

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {

        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, AboutMeCount obj, String arg3) {
            if (obj.getNum() > 0) {
                meRelatedCountTv.setVisibility(View.VISIBLE);
                meRelatedCountTv.setText(obj.getNum() + "");
                if (obj.getNum() > 99) meRelatedCountTv.setText("99+");
            }
        }

        //		/*
        //		 * (non-Javadoc)
        //		 * @see com.shwread.http.base.ObjectHttpResponseHandler#onFailure(int,
        //		 * org.apache.http.Header[], java.lang.String, java.lang.Throwable)
        //		 */
        //		@Override
        //		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        //			Toast.makeText(context,responseString+"失败", 2222).show();
        //		}
        //
        //		/*
        //		 * (non-Javadoc)
        //		 * @see com.shwread.http.base.ObjectHttpResponseHandler#onSuccess(int,
        //		 * org.apache.http.Header[], java.lang.Object, java.lang.String)
        //		 */
        //		@Override
        //		public void onSuccess(int statusCode, Header[] headers, AboutMeCount object, String responseString) {
        //			Toast.makeText(context,responseString+"chengg", 2222).show();
        //			if(object != null && object.getNum() > 0)
        //			{
        //				meRelatedCountTv.setVisibility(View.VISIBLE);
        //				meRelatedCountTv.setText(""+object.getNum());
        //			}
        //		}
        //
        //		/*
        //		 * (non-Javadoc)
        //		 * @see com.shwread.http.base.ObjectHttpResponseHandler#getType()
        //		 */
        //		@Override
        //		public Type getType() {
        //			// TODO Auto-generated method stub
        //			return new TypeToken<AboutMeCount>()
        //			{
        //			}.getType();
        //		}

    }

    void setListener() {
        //		messageLayout.setOnClickListener(this);
        //		ivPersion.setOnClickListener(this);
        //		ivManager.setOnClickListener(this);
        //		ivSetting.setOnClickListener(this);
        titleView.setOnClickListener(this);
        postmsg.setOnClickListener(this);
        //		rlayNoNetTopTip.setOnClickListener(this);
        meRelatedInputBoxLl.setOnClickListener(this);
        meRelatedButtonLl.setOnClickListener(this);

        contentView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                if (contentView.isHeaderShown()) { // 下拉刷新
                    refresh();
                } else if (contentView.isFooterShown()) { // 上拉加载
                    loadMore();
                }
            }
        });
    }

    private void setPageInfo() {
        if (Const.UserRole.equals("2")) {
            pagetype = 2;
            //			ivPersion.setVisibility(View.VISIBLE);
            //			ivManager.setVisibility(View.GONE);
        } else if (Const.UserRole.equals("1")) {
            pagetype = 1;
            //			ivManager.setVisibility(View.VISIBLE);
            //			ivPersion.setVisibility(View.GONE);
        } else if (Const.UserRole.equals("0")) {
            pagetype = 0;
            //			ivPersion.setVisibility(View.GONE);
            //			ivManager.setVisibility(View.GONE);
        }
    }

    /**
     * 如果页面有数据则清空数据 重新加载
     */
    private void clearPage() {
        // if (ll_interaction_contentview != null)
        // {
        // ll_interaction_contentview.removeAllViews();
        // }
        ll_interaction_contentview.addView(contentItemView);
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        // TODO
        if (NetUtil.isNetworkConnected(this)) {
            NewActionHelp.qryReplyRelateMeCount(this, new GetAboutMeCount());
            contentItemView.getInteractionData(1);
            //			rlayNoNetTopTip.setVisibility(View.GONE);
        } else {
            //			rlayNoNetTopTip.setVisibility(View.VISIBLE);
            contentView.onRefreshComplete();
            new NoNetDialog(this).show();
        }
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        if (!NetUtil.isNetworkConnected(this)) {

            //			rlayNoNetTopTip.setVisibility(View.VISIBLE);
        } else {
            //			rlayNoNetTopTip.setVisibility(View.GONE);

            if (contentItemView.getDataSize() == 0) {
                PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
            } else {
                if (contentItemView.getHasMore()) {
                    // 加载下一页
                    contentItemView.getNextPage();
                    return;
                } else if (contentItemView.isGotMaxSize()) {
                    // 已经达到了最大条数，
                    //				PullToRefreshUtil.setLoadLabel(contentView, "已经达到了最大条数");
                    PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
                } else {
                    // 没有更多了， 所以不再加载下一页
                    PullToRefreshUtil.setLoadLabel(contentView, "没有更多了");
                }
            }
        }
        contentView.onRefreshComplete();
    }


    private void qryUnReadTotal() {
        long lastQryTime = QyreaderPerferencesUtil.getInstance(this, Const.phone_number).getLastQryTime();
        if (pagetype == 1)
            new QryUnReadActivityAction(this, lastQryTime, new GetUnReadActivity()).start();
        new QryUnReadTotalAction(this, DefaultConsts.TYPE_WRITESOURCE_ENTERPRISE, new GetUnreadAction(true)).start();
        new QryUnReadTotalAction(this, DefaultConsts.TYPE_WRITESOURCE_SYSTEM, new GetUnreadAction(false)).start();
    }

    private Integer tempE = null, tempS = null;

    private class GetUnreadAction
            extends
            BaseAction {
        boolean flag;

        public GetUnreadAction(boolean flag) {
            this.flag = flag;
        }

        @Override
        public void OK(Object obj) {
            final int count = (Integer) obj;
            if (flag) {
                // if(count>0) Const.UNREAD_MSG_COUNT_E = count;
                tempE = count;
            } else {
                // if(count>0) Const.UNREAD_MSG_COUNT_S = count;
                tempS = count;
            }
            if (tempE != null && tempS != null)
            // if (Const.UNREAD_MSG_COUNT_E != null && Const.UNREAD_MSG_COUNT_S
            // != null)
            {
                getUIHandler().post(new Runnable() {
                    @Override
                    public void run() {
                        boolean res = (tempE == 0 && tempS == 0) ? false : true;
                        // boolean res = (Const.UNREAD_MSG_COUNT_E == 0 &&
                        // Const.UNREAD_MSG_COUNT_S == 0) ? false : true;
                        //						ivMsgUnread.setVisibility(res ? View.VISIBLE : View.GONE);
                    }
                });
            }
        }
    }

    class GetUnReadActivity
            extends
            BaseAction {

        @Override
        public void OK(Object obj) {
            String hasNew = (String) obj;
            //			if (hasNew.equals("y"))
            //			{
            //				ivManagerRedDot.setVisibility(View.VISIBLE);
            //			}
            //			else
            //			{
            //				ivManagerRedDot.setVisibility(View.GONE);
            //			}

        }

    }

    private void onLeave() {
        registerMsgUnreadInfoObserver(false);

        registerSystemMessageObservers(false);

    }

    @Override
    protected void onStop() {
        super.onStop();
        onLeave();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.new_common_header_msg_layout:
                goMessagePage();
                break;
            case R.id.new_common_header_persion:// 跳转到显示联系人界面
                //				Intent intent = new Intent();
                //				intent.setClass(context, NewIntercationCenterToLinkmanActivity.class);
                //				context.startActivity(intent);
                Intent intent = new Intent();
                intent.setClass(this, ContactMainActivity.class);
                startActivity(intent);
                break;
            //			case R.id.new_common_header_manager:
            //				new ManagerClickPopupWindow(context, new IManagerClickPopListener()
            //				{
            //
            //					@Override
            //					public void ok(int i, ManagerClickPopupWindow pop) {
            //						if (i == 0)
            //						{
            //							Intent actvListIntent = new Intent(bActivity, NewInteractionActvListActivity.class);
            //							bActivity.startActivity(actvListIntent);
            //							onLeave();
            //
            //						}
            //						if (i == 1)
            //						{
            //							//Toast.makeText(context, "聊天列表", 0).show();
            //							Intent intent = new Intent();
            //							// intent.setClass(context, NewInteractionDetailsActivity.class);
            //							intent.setClass(context, ContactMainActivity.class);
            //							context.startActivity(intent);
            //							onLeave();
            //						}
            //						pop.dismiss();
            //					}
            //				}).showAsDropDown(ivManager, -ScreenUtil.dip2px(47), ScreenUtil.dip2px(-10));
            //				break;
            //			case R.id.new_common_header_setting:// 设置按钮
            //				bActivity.goPersonalActivity();
            //				break;
            case R.id.new_common_title_layout:
                titleDoubleClick();
                break;
            //TODO
            //			case R.id.new_interaction_test_add_layout:
            case R.id.new_interaction_center_postmsg:
                if (postmsgAnimation != null && postmsgAnimation.isRunning()) {
                    postmsgAnimation.stop();
                }
                Intent postmsg = new Intent();
                postmsg.putExtra("releaseType", releaseType);
                postmsg.setClass(this, NewInteractionCenterUserPublishActivity.class);
                //				context.startActivity(postmsg);
                startActivityForResult(postmsg, DefaultConsts.START_PUBLISH_THEME_ACTIVITY);
                break;
            case R.id.new_i_no_net_top_tip_rlay:
                startWirelessSettingsActivity(this);
                break;
            case R.id.me_related_input_box_ll:
//                bActivity.changePage(NewInteractionCenterUserPublishPage.getInstance(this), DEFAULT_STATUS);
                Intent postmsg1 = new Intent();
                postmsg1.setClass(this, NewInteractionCenterUserPublishActivity.class);
                //				context.startActivity(postmsg);
                postmsg1.putExtra("releaseType", releaseType);
                startActivityForResult(postmsg1, DefaultConsts.START_PUBLISH_THEME_ACTIVITY);
                break;
            case R.id.me_related_button_ll:
                if (meRelatedCountTv.isShown()) {
                    meRelatedCountTv.setVisibility(View.GONE);
                }
                NewActionHelp.readReplyRelateMe(this, new ReadReplyRelateMe());
                Intent intent2 = new Intent();
                intent2.setClass(this, WithMeRelatedActivity.class);
                startActivity(intent2);
                break;
        }
    }

    private class ReadReplyRelateMe
            extends
            TextHttpResponseHandler {

        @Override
        public void onFailure(int arg0, Header[] arg1, String arg2, Throwable arg3) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onSuccess(int arg0, Header[] arg1, String arg2) {
            // TODO Auto-generated method stub

        }

    }

    /**
     * 跳转到网络设置页面
     *
     * @param context
     */

    private void startWirelessSettingsActivity(Activity context) {
        try {
            Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
            intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {

        }
    }

    private void goMessagePage() {
        startActivity(new Intent(this, MessageActivity.class));
    }

    private int clickCount;
    private long preClickTime;
    /**
     * 双击有效时间500毫秒
     */
    private final int defalultValue = 500;

    /**
     * 标题栏双击，回到顶部
     */
    private void titleDoubleClick() {
        if (clickCount == 0) {
            preClickTime = System.currentTimeMillis();
            clickCount++;
        } else if (clickCount == 1) {
            if ((System.currentTimeMillis() - preClickTime) < defalultValue) {
                gotoTop();
            }
            clickCount = 0;
            preClickTime = 0;
        } else {
            clickCount = 0;
            preClickTime = 0;
        }
    }

    /**
     * 回到顶部
     */
    private void gotoTop() {
        contentItemView.post(new Runnable() {
            @Override
            public void run() {
                contentView.getRefreshableView().scrollTo(0, 0);
            }
        });
    }

    private GuideDialog dialog;
    private boolean showHelp;
    private QyreaderPerferencesUtil util;
    private ImageView postmsg;
    private Button ivNewMsg;

    private void initGuide() {
        util = QyreaderPerferencesUtil.getInstance(this, DefaultConsts.FIRST_TAG);
        dialog = new GuideDialog(this, R.layout.enterprise_page_firstin);
    }

    private void showGuide() {
        if (util == null || dialog == null) {
            initGuide();
        }
        showHelp = util.getShowEnterpriseHelp();
        if (showHelp) {
            if (null != dialog && !dialog.isShowing()) {
                dialog.show();
            }
            util.setShowEnterpriseHelp(false);
        }
    }

    /**
     * 未读消息数量观察者
     */

    private void registerMsgUnreadInfoObserver(boolean register) {
        if (register) {
            ReminderManager.getInstance().registerUnreadNumChangedCallback(this);
        } else {
            ReminderManager.getInstance().unregisterUnreadNumChangedCallback(this);

        }
    }

    /**
     * 注册/注销新消息
     *
     * @param register
     */
    private void registerSystemMessageObservers(boolean register) {
        NIMClient.getService(MsgServiceObserve.class).observeReceiveMessage(incomingMessageObserver, true);
    }

    /**
     * 定义一个观察者
     */
    Observer<List<IMMessage>> incomingMessageObserver = new Observer<List<IMMessage>>() {
        @Override
        public void onEvent(List<IMMessage> messages) {
            updateRedDot(true);
        }
    };

    @Override
    public void onUnreadNumChanged(ReminderItem item) {
        boolean b;
        if (item != null && item.getUnread() > 0) {
            b = true;
        } else {
            b = false;
        }
        updateRedDot(b);
    }

    /**
     * 刷新小红点的状态
     *
     * @param b
     */

    private void updateRedDot(final boolean b) {
        if (pagetype == 1) {
            getUIHandler().post(new Runnable() {

                @Override
                public void run() {
                    //					ivManagerRedDot.setVisibility(b ? View.VISIBLE : View.GONE);

                }
            });
        } else if (pagetype == 2) {
            getUIHandler().post(new Runnable() {

                @Override
                public void run() {
                    //					ivPersionRedDot.setVisibility(b ? View.VISIBLE : View.GONE);
                }

            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BaseBusinessActivity.COMMENTS_REQUEST_CODE) {
            NewActionHelp.qryReplyRelateMeCount(this, new GetAboutMeCount());
            Bundle b = data.getBundleExtra("bundle_data");
            contentItemView.updateComment(b.getInt("position"), b.getInt("count"));
        } else if (requestCode == DefaultConsts.START_PUBLISH_THEME_ACTIVITY) {
            contentItemView.getInteractionData(1);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        qryUnReadTotal();
    }
}
